import cgi
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.util import login_required
from table import Candidate

class MainPage(webapp.RequestHandler):

    @login_required
    def get(self):
        wr = self.response.out.write
        wr("<html><body>")
        wr("<div align=center><h2>Online Test</h2></div>")
        user = users.get_current_user()
        cand = Candidate.all().filter( "email =",user.email()).get()
        if cand:
            wr("<br/><br/><br/>")
            wr("<div align=center>Your details:</div></br>")
            wr("<table align=center border = 1 cellspacing=2 cellpadding=5>")
            wr('<th width=50%></th><th></th>')
            for cnt in xrange (0,len(cand.details),2):
                wr("<tr><td align=left><b>%s</b></td><td align=center>%s</td></tr>"%(cand.details[cnt],cand.details[cnt+1]))
            wr("</table>")

            wr("<div align = center>%s</div>"%cand.instructions)


            wr("""<form action = '/verify' method = 'POST'>""")
            if not cand.has_acknowledged:                
                wr("""
                    <div align = center>
                    <label>Click Acknowledge to enroll to the test</label>
                    <input type = 'submit' value = 'Acknowledge'/>
                    </div>
                """)
            else:
                wr("""
                    <div align = center>
                    <label>'Thanks For Acknowledging!'</label>
                    </div>
                """)
            wr(""" </form> """)
            url = users.create_logout_url(self.request.uri)
            wr("<br/><br/><div align=center><a href=%s>Logout</a></div>"%(url))                
        else:
            wr("%s, Inavlid Email ID"%user.nickname())
            url = users.create_logout_url(self.request.uri)
            self.response.out.write("<br/><a href=%s>Logout</a> and try again"%(url)) 
        wr('</body><html>')
                     
    def post(self):            
        user = users.get_current_user()
        cand = Candidate.all().filter("email =",user.email()).get()
        if cand and not cand.has_acknowledged:
            cand.has_acknowledged = True 
            cand.put()
        self.redirect('/verify')    
                
application = webapp.WSGIApplication(
                                     [('/verify', MainPage)],
                                     debug=True)

def main():     
  run_wsgi_app(application)

if __name__ == "__main__":
  main()                                        
